<template>
  <!-- label-position 对齐方式 -->
  <el-form
    label-position="left"
    label-width="10px"
    :model="registerData"
    :rules="rules"
    ref="formData"
  >
    <el-form-item prop="username">
      <el-input
        v-model="registerData.username"
        prefix-icon="el-icon-user"
      ></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="registerData.password"
        prefix-icon="el-icon-lock"
        show-password
      ></el-input>
    </el-form-item>
    <el-form-item prop="captcha">
      <el-row>
        <el-col :span="16">
          <el-input
            v-model="registerData.captcha"
            prefix-icon="el-icon-circle-check"
          ></el-input>
        </el-col>
        <el-col :span="8">
          <!-- http://127.0.0.1:7001/api/imagecode用后端的接口地址获取验证码图片, 后端已经给出返回格式 -->
          <img
            src="http://127.0.0.1:7001/imagecode"
            style="margin-left: 10px"
            ref="imageCaptcha"
            @click="updateCaptcha"
          />
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit" style="width: 95%"
        >注册</el-button
      >
    </el-form-item>
    <router-link to="/login" class="register">已有账号？立即登录吧</router-link>
    <el-form-item prop="checked">
      <el-checkbox v-model="registerData.checked">
        <p>
          阅读并接受
          <a href="javascript:;"> 《小兔仙用户协议》 </a>
          及
          <a href="javascript:;"> 《小兔仙隐私权保护声明》 </a>
        </p>
      </el-checkbox>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
import { Component, Vue, Ref } from "vue-property-decorator";
import { registerUser } from "@/api/index";
@Component({
  name: "NormalForm",
  components: {},
})
export default class NormalForm extends Vue {
  registerData = {
    username: "",
    password: "",
    captcha: "",
    type: "normal", // 默认类型是 normal
    checked: true,
  };
  private validateName = (rule: any, value: string, callback: any) => {
    const reg = /^[A-Za-z0-9]{6,}$/;
    if (!value) {
      callback(new Error("请输入用户名"));
    } else if (value.length < 6) {
      callback(new Error("用户名至少是6位"));
    } else if (!reg.test(value)) {
      callback(new Error("用户名只能是数字或字母"));
    } else {
      callback();
    }
  };
  private validatePwd = (rule: any, value: string, callback: any) => {
    const reg =
      /^(?:(?=.*[0-9].*)(?=.*[A-Za-z].*)(?=.*[,\.#%'\+\*\-:;^_`].*))[,\.#%'\+\*\-:;^_`0-9A-Za-z]{8,}$/;
    if (!value) {
      callback(new Error("请输入密码"));
    } else if (value.length < 8) {
      callback(new Error("密码至少是8位"));
    } else if (!reg.test(value)) {
      callback(new Error("密码必须是数字字母符号组合"));
    } else {
      callback();
    }
  };
  private validateCapt = (rule: any, value: string, callback: any) => {
    const reg = /^[A-Za-z0-9]{4}$/;
    if (!value) {
      callback(new Error("请输入验证码"));
    } else if (value.length < 4) {
      callback(new Error("验证码至少是4位"));
    } else if (!reg.test(value)) {
      callback(new Error("验证码必须是数字或字母组成"));
    } else {
      callback();
    }
  };
  private validateChecked = (rule: any, value: string, callback: any) => {
    if (!value) {
      callback(new Error("请阅读并同意用户协议"));
    } else {
      callback();
    }
  };
  // 校验规则
  rules = {
    username: [{ validator: this.validateName, trigger: "blur" }],
    password: [{ validator: this.validatePwd, trigger: "blur" }],
    captcha: [{ validator: this.validateCapt, trigger: "blur" }],
    checked: [{ validator: this.validateChecked, trigger: "change" }],
  };
  // 点击更新验证码
  @Ref() readonly imageCaptcha!: HTMLImageElement; // imageCaptcha! !一定有
  private updateCaptcha() {
    // 强制转成 any 有点不符合 TS 的思想
    //   (this.$refs.imageCaptcha as any).src = `http://127.0.0.1:7001/api/imagecode?r=${Math.random()}`
    this.imageCaptcha.src = `http://127.0.0.1:7001/imagecode?r=${Math.random()}`;
  }
  @Ref() readonly formData!: HTMLFormElement;
  private onSubmit() {
    this.formData.validate((valid: boolean) => {
      if (valid) {
        // 校验通过, 发送请求
        registerUser(this.registerData)
          .then((response: any) => {
            console.log(response);
            if (response.status === 200) {
              // 注册成功跳转登录界面
              (this as any).$message.success("注册成功");
              this.$router.push("/login");
              this.updateCaptcha();
            } else {
              (this as any).$message.error(response.data.msg);
            }
          })
          .catch((e) => {
            // 💥注意点: (）可以代表一个函数的调用属性 如果()后面没有加 ; js会默认后面的()是前面属性方法的调用属性
            // 更新验证码
            this.updateCaptcha();
            (this as any).$message.error(e.response.data.msg);
          });
      } else {
        this.updateCaptcha();
        (this as any).$message.error("数据格式不对");
      }
    });
  }
  // 重置表单
  public resetForm() {
    this.formData.resetFields();
  }
}
</script>

<style lang="scss" scoped>
a {
  text-decoration: none;
}
.el-col {
  height: 40px;
}
.el-form {
  padding-right: 20px;
  box-sizing: border-box;
}
.register {
  display: block;
  font-size: 15px;
  color: #407ffe;
  text-align: center;
  // margin-bottom: 10px;
  text-decoration: none;
}
</style>
